layui.define(['table','form'],function (exports) {
    var form = layui.form
        ,table = layui.table
        ,tableInit = null;
    var controller = {
        index:function () {
            tableInit = table.render({
                elem: '#table-page'
                ,url: "index"
                ,toolbar: "#toolbar"
                ,defaultToolbar:[]
                ,parseData: function(res){ //res 即为原始返回的数据
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.data.total, //解析数据长度
                        "data": res.data.list //解析数据列表
                    };
                }
                ,response: {
                    statusCode: 1 //规定成功的状态码，默认：0
                }
                ,cellMinWidth:100
                ,cols: [[
                    {fixed:'left', minWidth:10, type: 'checkbox'}
                    ,{field:'id', title: 'ID', sort: true}
                    ,{field:'username', title: '用户名'}
                    ,{field:'nickname', title: '昵称'}
                    ,{field:'phone', title: '手机号',minWidth:120}
                    ,{field:'email', title: '邮箱',minWidth:170}
                    ,{templet:function (d) {
                            if(d.ParentAdmin){
                                return d.ParentAdmin.username;
                            }
                            return '无';
                        }, title: '上级管理员'}
                    ,{field:'status',title: '状态',templet:function (d) {
                            if(d.status){
                                return '<input type="checkbox" name="post[status]" value="1" data-id="'+d.id+'" checked lay-skin="switch" lay-filter="status" lay-text="正常|禁用">';
                            }
                            return '<input type="checkbox" name="post[status]" value="1" data-id="'+d.id+'" lay-skin="switch" lay-filter="status" lay-text="正常|禁用">';
                        }}
                    ,{field:'login_count', title: '登录次数'}
                    ,{field:'login_time', title: '登录时间',minWidth:160}
                    ,{field:'login_ip', title: '登录ip'}
                    ,{field:'last_login_time', title: '上次登录时间',minWidth:160}
                    ,{field:'last_login_ip', title: '上次登录ip'}
                    ,{fixed: 'right', align:'center', toolbar: '#action', width:200}
                ]]
                ,page: true
            });

            //监听工具条
            table.on('tool(table-page)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                var data = obj.data; //获得当前行数据
                var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

                if(layEvent === 'auth'){ //授权
                    controller.open_auth(data.id);
                } else if(layEvent === 'del'){ //删除
                    controller.delete_api(data.id);
                } else if(layEvent === 'edit'){ //编辑
                    controller.open_edit(data.id);
                } else if(layEvent === 'LAYTABLE_TIPS'){
                    layer.alert('Hi，头部工具栏扩展的右侧图标。');
                }
            });
            //监听事件
            table.on('toolbar(table-page)', function(obj){
                var checkStatus = table.checkStatus(obj.config.id);
                switch(obj.event){
                    case 'add':
                        controller.open_edit();
                        break;
                    case 'delete':
                        controller.delete_api(checkStatus.data);
                        break;
                }
            });
            form.on('switch(status)', function(data){
                var id = $(data.elem).data('id');
                var load_index = layer.load();
                $.post("status",{ids:[id],status:data.elem.checked? 1 : 0})
                    .success(function (response) {
                        if(response.code){
                            notice.success(response.msg);
                        }else{
                            notice.error(response.msg);
                        }
                    })
                    .error(function (err) {
                        notice.error(err.status+" "+err.statusText);
                    })
                    .complete(function () {
                        layer.close(load_index);
                    });
            });
            form.on('submit(search-btn)',function (data) {
                tableInit.reload({
                    where: data.field
                });
                return false;
            });
        },
        open_edit:function (id = 0) {
            var url = '';
            var title;
            if(id){
                url = '/admin/admin/edit/id/'+id;
                title = '编辑';
            }else{
                url = '/admin/admin/add';
                title = '添加';
            }
            parent.layer.open({
                type:2
                ,title:title
                ,content:url
                ,area:['50%','80%']
                ,maxmin:true
                ,end:function () {
                    tableInit.reload();
                }
            });
        },
        add:function(){
            controller.edit();
        },
        edit:function () {
            /* 监听提交 */
            form.on('submit(submit-form)', function(data){
                var load_index = layer.load();
                $.post($("form[lay-filter=edit-form]").get(0).action,data.field)
                    .success(function (response) {
                        if(response.code){
                            notice.success(response.msg);
                            setTimeout(function () {
                                parent.layer.closeAll();
                            },1000);
                        }else{
                            notice.error(response.msg);
                        }
                    })
                    .complete(function () {
                        layer.close(load_index);
                    });
                return false;
            });

        },
        delete_api:function (data) {
            layer.confirm("您真的要删除吗？",function (index) {
                layer.close(index);
                var ids = [];
                if(data instanceof Array){
                    layui.each(data,function (k,item) {
                        ids.push(item.id);
                    });
                }else{
                    ids = [data];
                }
                var load_index = layer.load();
                $.post("delete",{ids:ids})
                    .success(function (response) {
                        if(response.code){
                            notice.success(response.msg);
                            setTimeout(function () {
                                tableInit.reload();
                            },1000);
                        }else{
                            notice.error(response.msg);
                        }
                    })
                    .complete(function () {
                        layer.close(load_index);
                    });
            });
        },
        auth:function () {
            /* 监听提交 */
            form.on('submit(submit-auth-form)', function(data){
                var load_index = layer.load();
                $.post($("form[lay-filter=auth-form]").get(0).action,data.field)
                    .success(function (response) {
                        if(response.code){
                            notice.success(response.msg);
                            setTimeout(function () {
                                parent.layer.closeAll();
                            },1000);
                        }else{
                            notice.error(response.msg);
                        }
                    })
                    .complete(function () {
                        layer.close(load_index);
                    });
                return false;
            });
        },
        open_auth:function (user_id) {
            var title = "授权";
            var url = "/admin/admin/auth/id/"+user_id;
            parent.layer.open({
                type:2
                ,title:title
                ,content:url
                ,area:['50%','50%']
                ,maxmin:true
                ,end:function () {

                }
            });
        },
        info:function () {
            //自定义验证
            form.verify({
                nickname: function(value, item){ //value：表单的值、item：表单的DOM对象
                    if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
                        return '用户名不能有特殊字符';
                    }
                    if(/(^\_)|(\__)|(\_+$)/.test(value)){
                        return '用户名首尾不能出现下划线\'_\'';
                    }
                    if(/^\d+\d+\d$/.test(value)){
                        return '用户名不能全为数字';
                    }
                }
            });
            //设置我的资料
            form.on('submit(setmyinfo)', function(obj){
                //提交修改
                var load_index = layer.load();
                $.post('',obj.field)
                    .success(function (response) {
                        if(response.code){
                            notice.success(response.msg);
                        }else{
                            notice.error(response.msg);
                        }
                    })
                    .complete(function () {
                        layer.close(load_index);
                    });
                return false;
            });
        },
        password:function () {
            //自定义验证
            form.verify({
                pass: [
                    /^[\S]{6,12}$/
                    ,'密码必须6到12位，且不能出现空格'
                ]
                //确认密码
                ,repass: function(value){
                    if(value !== $('#LAY_password').val()){
                        return '两次密码输入不一致';
                    }
                }
            });
            //设置密码
            form.on('submit(setmypass)', function(obj){
                var load_index = layer.load();
                $.post('',obj.field)
                    .success(function (response) {
                        if(response.code){
                            notice.success(response.msg);
                            setTimeout(function () {
                                parent.window.location.href = '/admin/login/login';
                            },1000);
                        }else{
                            notice.error(response.msg);
                        }
                    })
                    .complete(function () {
                        layer.close(load_index);
                    });
                return false;
            });
        }
    };
   exports('admin_admin',controller)
});